package com.cgnpc.scp.common.bean;

import com.cgnpc.scp.common.config.CustomSpringConfig;
import com.cgnpc.scp.common.utils.FileUtil;
import com.cgnpc.scp.common.utils.IOUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.ResourceHttpMessageConverter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

public class CustomDownloadFileResourceHttpMessageConverter extends ResourceHttpMessageConverter {
    private static final Logger LOGGER = LoggerFactory.getLogger(CustomDownloadFileResourceHttpMessageConverter.class);

    @Override
    protected Resource readInternal(Class<? extends Resource> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        if (CustomDownloadFileInputStreamResource.class == clazz) {
            CustomDownloadFileInputStreamResource customDownloadFileInputStreamResource = null;
            FileOutputStream localFileOut = null;

            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyMM");
                Date nowDate = new Date();
                String fileName = "tempFile-" + System.currentTimeMillis() + "-" + UUID.randomUUID().toString() + "-notName";
                File fileInsideTempDir = CustomSpringConfig.getInsideTempDir();
                File fileDir = new File(fileInsideTempDir, "downloadFileDir/" + sdf.format(nowDate));
                FileUtil.mkdirs(fileDir);
                File localTempFilePath = new File(fileDir, fileName);
                LOGGER.info("CustomDownloadFileResourceHttpMessageConverter;localTempFilePath:{};", localTempFilePath);

                InputStream inputStream = inputMessage.getBody();
                byte[] arrReadData = new byte[1024 * 1024 * 2];
                int readLen = 0;

                localFileOut = new FileOutputStream(localTempFilePath);

                while ((readLen = inputStream.read(arrReadData)) != -1) {
                    localFileOut.write(arrReadData, 0, readLen);
                    localFileOut.flush();
                }

                customDownloadFileInputStreamResource = new CustomDownloadFileInputStreamResource(
                        inputStream
                        , "Used getFile method"
                        , localTempFilePath
                );
            } catch (Exception e) {
                LOGGER.error("error;", e);
                throw new RuntimeException(e);
            } finally {
                IOUtil.closeStream(localFileOut);
            }

            return customDownloadFileInputStreamResource;
        } else {
            return super.readInternal(clazz, inputMessage);
        }
    }

}
